package org.springframework.security.core.context;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.SpringSecurityCoreVersion;
import org.springframework.util.ObjectUtils;

import java.io.Serial;

/**
 * @author Dillon
 * @date 2024/6/28
 * @slogan 致敬大师 致敬未来的你
 * @desc SecurityContext 默认的缓存实现类
 */
public class SecurityContextImpl implements SecurityContext {

	/**
	 * 序列化标记
	 */
	@Serial
	private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID;

	/**
	 * 认证实现类
	 */
	private Authentication authentication;

	/**
	 * 构造函数
	 */
	public SecurityContextImpl() {
	}

	/**
	 * 构造函数
	 *
	 * @param authentication 认证实现类
	 */
	public SecurityContextImpl(Authentication authentication) {
		this.authentication = authentication;
	}

	/**
	 * 重写equals
	 *
	 * @param obj 比较对象
	 * @return 对象是否相等
	 */
	@Override
	public boolean equals(Object obj) {
		if (obj instanceof SecurityContextImpl other) {
			if ((this.getAuthentication() == null) && (other.getAuthentication() == null)) {
				return true;
			}
			if ((this.getAuthentication() != null) && (other.getAuthentication() != null)
					&& this.getAuthentication().equals(other.getAuthentication())) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 获取认证对象
	 * 认证对象只是参与认证，是否认证成功不确定
	 *
	 * @return 认证对象
	 */
	@Override
	public Authentication getAuthentication() {
		return this.authentication;
	}

	/**
	 * 复写 hashCode
	 *
	 * @return hashCode值
	 */
	@Override
	public int hashCode() {
		return ObjectUtils.nullSafeHashCode(this.authentication);
	}

	/**
	 * 设置认证对象
	 *
	 * @param authentication 认证对象
	 */
	@Override
	public void setAuthentication(Authentication authentication) {
		this.authentication = authentication;
	}

	/**
	 * 复写 toString
	 *
	 * @return toString 表示方法
	 */
	@Override
	public String toString() {
		StringBuilder sb = new StringBuilder();
		sb.append(getClass().getSimpleName()).append(" [");
		if (this.authentication == null) {
			sb.append("空的 Authentication");
		} else {
			sb.append("Authentication=").append(this.authentication);
		}
		sb.append("]");
		return sb.toString();
	}

}
